<?php

namespace Admin\Frontend\Controllers;

use Helpers\Main;
use Helpers\Assets;
use Helpers\Template;
use Helpers\XhException;
use Modules\Power;
use Modules\School;
use Services\ResBase;
use Services\UserService;
use Admin\Models\sys\XhsysEnum;
use Admin\Models\user\XhsysUser;
use Admin\Models\app\XhappStore;
use Admin\Models\school\XhschoolInfo;
use Admin\Models\school\XhschoolOpenclass;
use Admin\Models\school\XhschoolClasslist;
use Admin\Models\school\XhschoolClassteacher;
use Admin\Models\school\XhschoolClassstudent;
use Admin\Models\school\XhschoolAutoclasserror;


class ClassController extends ControllerBase
{
    private $classErrorEnum = [
        'type'      => [1 => '班级', 2 => '教师', 3 => '学生', 4 => '其他', 5 => '分组'],
        'classType' => [0 => '行政班', 1 => '培优班'],
        'status'    => [1 => '待处理', 2 => '处理成功', 3 => '处理失败']
    ];

    /**
     * 自动开班失败列表
     *
     * @return \Phalcon\Mvc\View|string
     *
     * create by ck 20180726
     */
    public function autoClassErrorAction()
    {
        if (!Power::exist('School_ClassError')) {
            return $this->sendViewError('无查看权限');
        }
        $this->view->setTemplateBefore('listForm');
        Main::showNavPosition();
        Assets::easyUI('js/class/autoClassError.js');
        $listButtonArr = $listSearchArr = [];
        if (Power::exist('School_ClassError_Edit')) {
            $listButtonArr[] = ['plain' => 'true', 'id' => 'bt_list_redo', 'text' => '一键重试', 'icon' => 'fa-refresh'];
        }
        $listSearchArr[] = ['type' => 'select', 'id' => 'list_status', 'data' => [0 => '-选择状态-'] + $this->classErrorEnum['status']];
        return $this->view->setVars([
            'List'          => Template::createList('list', 'Class_AutoClassError', [
                'searchToolbar' => Template::createSearchToolBar($listSearchArr, !!$listButtonArr),
                'buttonToolbar' => Template::createButtonToolBar($listButtonArr)
            ]),
        ]);
    }

    /**
     * 获取自动开班失败列表
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20180726
     */
    public function getAutoClassErrorAction()
    {
        $status     = $this->request->getPost('status', 'int');
        $params = [
            'conditions' => [],
            'bind'       => [],
            'order'      => 'id desc'
        ];
        if ($status) {
            $params['conditions'][] = 'status = :status:';
            $params['bind']['status'] = $status;
        }
        $params['conditions'] = implode(' AND ', $params['conditions']);
        $data = Main::runModelPage('\\Admin\\Models\\school\\XhschoolAutoclasserror', $params, $this->classErrorEnum);
        School::runName($data['rows'], ['schoolId' => 'schoolName']);
        return $this->sendJsonResponse($data);
    }

    /**
     * 重新处理失败
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20180726
     */
    public function redoAutoClassAction()
    {
        $id = $this->request->getPost('id', 'int');
        if (!$id) {
            return $this->sendErrorResponse(400, '缺少id');
        }
        if (!Power::exist('School_ClassError_Edit')) {
            return $this->sendErrorResponse(403, '无操作权限');
        }
        try {
            $obj = XhschoolAutoclasserror::findFirst($id);
            if (!$obj) {
                throw new XhException('找不到记录');
            }
            if ($obj->status == 2) {
                throw new XhException('该记录已处理');
            }
            switch ($obj->type) {
                case 1:
                    //创建班级
                    UserService::createClass($obj->schoolId, $obj->className, 20 . substr($obj->className, 0, 2), $obj->classType, $obj->folderId);
                    //todo 将学生加入班级
                    break;
                case 2:
                    //教师加入班级
                    $subjectId = array_search($obj->subject, ResBase::getDictionaries('subject'));
                    if (!$subjectId) {
                        throw new XhException('找不到对应科目');
                    }
                    UserService::addClassTch($obj->schoolId, $obj->classId, $obj->tchId, $subjectId);
                    break;
                case 3:
                    //学生加入班级
                    UserService::addClassMember($obj->schoolId, $obj->classId, $obj->studIds);
                    break;
                case 5:
                    //创建分组
                    UserService::createFolder($obj->schoolId, $obj->className, 20 . substr($obj->className, 0, 2));
                    break;
                default:
                    throw new XhException('该记录暂时无法处理');
            }
            $obj->status = 2;
            if (!$obj->save()) {
                throw new XhException('处理成功，标记失败');
            }
            return $this->sendSuccessResponse('处理成功');
        } catch (XhException $e) {
            if (isset($obj)) {
                $obj->status = 3;
                $obj->save();
            }
            return $this->sendErrorResponse(500, $e->getMessage(), $e->getDescription());
        }
    }

    /**
     * 删除已存在数据库的旧记录，无记录或成功返回true，否则返回false
     *
     * @param $schoolId         --学校ID
     * @param $appCode          --应用编号
     * @param $teacherId        --教师ID
     * @return bool
     *
     * create by ck 20160815
     * modify by ck 20160929    代码化简，操作放入model中
     */
    function deleteOldClassInfo($schoolId, $appCode, $teacherId){
        $openClassId = XhschoolOpenclass::getOldOpenClassId($schoolId, $appCode, $teacherId);
        if(!$openClassId) return true;
        if(!XhschoolOpenclass::deleteRecordById($openClassId)) return false;                //删除开班记录
        if(!XhschoolClassteacher::deleteRecordByOpenClassId($openClassId)) return false;    //删除教师
        if(!XhschoolClasslist::deleteRecordByOpenClassId($openClassId)) return false;       //删除班级
        if(!XhschoolClassstudent::deleteRecordByOpenClassId($openClassId)) return false;    //删除学生
        return true;
    }

    /**
     * 根据教师ID，应用编号，学校ID获取开班信息，有信息则删除原有记录并插入新数据，返回开班ID
     * 无信息则还原已有信息，或插入新数据，返回开班ID
     *
     * @param $unitInfo
     * @return bool|int|null
     *
     * add by ck 20161009
     */
    function insertUnitData($unitInfo)
    {
        $openClass = XhschoolOpenclass::createRecord($unitInfo, 0);             //创建开班model
        if(!$openClass->insertData()) return false;
        foreach($unitInfo['oTeacher'] as $teacherInfo){                         //插入教师信息
            $teacher = XhschoolClassteacher::createRecord($teacherInfo['iTchId'], $openClass->iSOCId, 0);
            if(!$teacher->insertData()) return false;
        }
        if(isset($unitInfo['oClass'])) {
            foreach ($unitInfo['oClass'] as $classInfo) {                             //插入班级信息
                $class = XhschoolClasslist::createRecord($openClass->iSOCId, $classInfo['sClassName'], $classInfo['sClassId'], 0);
                if (!$class->insertData()) return false;
                if (!isset($classInfo['oStudent'])) continue;
                $studIdArr = array_column($classInfo['oStudent'], 'iStuId');
                if (empty($studIdArr)) continue;
                if (!XhschoolClassstudent::batchCreateStudent($studIdArr, $class->iSCLId, 0)) return false;   //批量插入学生信息
            }
        }
        return $openClass->iSOCId;
    }

    /**
     * 开班页面
     *
     * create by ck 20160815
     * modify by ck 20160928
     * modify by ck 20160929    结构更改
     * modify by ck 20161009    js更改，数据库插入操作使用额外方法
     * modify by ck 20161228    如果为古文刷题王，则使用另外的ip
     */
    public function openClassAction() {
        $this->view->pick('class/openClass');
        Assets::easyUI('js/class/openClass.js');
        $schoolId  = $this->request->getQuery('iSchoolId', 'int');
        $appCode   = $this->request->getQuery('iAppCode', 'string');
        $teacherId = $this->request->getQuery('iTeacherId', 'int');
        $schoolId && $appCode && $teacherId or die(Main::showMessageModal('缺少参数！', 109107001));
        $maskAppList = Main::getConfigByName('maskRelation');
        $maskAppList = explode(',', $maskAppList['app']);
        !in_array($appCode, $maskAppList) or die(Main::showMessageModal('此应用禁止开班！'));
        Power::exist('School_TeacherList_OpenClass') || School::hasPower($schoolId, true)
            or die(Main::showMessageModal('无操作权限！', 109107012));
        $this->view->setVar('navUl', $this->request->getQuery('navUl', 'string'));
        XhappStore::checkAppOutSchool($appCode) and $schoolId = 0;                  //如果为独立应用则设置学校ID为0
        $K = ['iAppCode' => $appCode, 'iTchId' => $teacherId];
        $schoolId and $K['iSchoolId'] = $schoolId;                                  //学校ID为0则不添加到参数中

        //add by ck 20161228    临时
//        if(in_array($appCode, ['1200'])){
//            $gwConfig = Main::getConfigByName('cRelation');
//            $gwConfig['ip'] = $gwConfig['gw'];
//            unset($gwConfig['gw']);
//            $data = Main::transitToCInterface($gwConfig, 'Web_GetStudTeacGroup', $K);
//        }
//        else{
            $data = Main::transitToCInterface('cRelation', 'Web_GetStudTeacGroup', $K);
//        }

//        $data = Main::transitToCInterface('cRelation', 'Web_GetStudTeacGroup', $K);
        $data = json_decode($data, true);
        $dbRollback = false;
        $this->db->begin();
        if($data['R'] == 200){                                                      //已有信息
            if(!self::deleteOldClassInfo($schoolId, $appCode, $teacherId)){
                $this->db->rollback();
                die(Main::showMessageModal('清理原记录失败，无法继续操作！', 109107002));
            }
            $unitInfo = json_decode($data['D'], true);
            $unitInfo = $unitInfo[0];
            isset($unitInfo['iSchoolId']) and $schoolId = $unitInfo['iSchoolId'];   //返回数据有学校ID则修改学校ID
            $openClassId = $this->insertUnitData($unitInfo);
            if(!$openClassId){
                $dbRollback = true;
                goto dealTrans;
            }
            $this->persistent->set('openClassId', $openClassId);
        }
        else{
            $openClassId = XhschoolOpenclass::getOldOpenClassId($schoolId, $appCode, $teacherId);
            if($openClassId) {
                $this->persistent->set('openClassId', $openClassId);                                        //设置开班ID
            }else{
                $openClass = XhschoolOpenclass::createRecord(array('iAppCode' => $appCode, 'iSchoolId' => $schoolId), 1);
                if(!$openClass->insertData()){
                    $dbRollback = true;
                    goto dealTrans;
                }
                $teacher = XhschoolClassteacher::createRecord($teacherId, $openClass->iSOCId, 1);
                if(!$teacher->insertData()){
                    $dbRollback = true;
                    goto dealTrans;
                }
                $this->persistent->set('openClassId', $openClass->iSOCId);                                  //设置开班ID
            }
        }
        dealTrans:
        if($dbRollback){
            $this->db->rollback();
            die(Main::showMessageModal('数据插入失败，无法继续操作！', 109107003));
        }
        $this->db->commit();
        $this->persistent->get('openClassId') or die(Main::showMessageModal('程序错误！', 109107004));
        $classInfoArr = XhschoolClasslist::findByOpenClassId($this->persistent->get('openClassId'));        //获取班级信息
        $tabStr = '';
        foreach($classInfoArr as $classInfo){                                                               //组成tab
            $frameName = 'class_' . $classInfo->iSCLId;
            $frameSrc  = $this->url->getBaseUri() . "Class/studentClassList?iSchoolId={$schoolId}&iSCLId={$classInfo->iSCLId}";
            $tabStr   .= "<div title='{$classInfo->sClassName}' data-options='closable:true,border:false'>";
            $tabStr   .= "<iframe name='{$frameName}' src='{$frameSrc}' frameborder='0' style='width:100%;height:100%;'></iframe>";
            $tabStr   .= '</div>';
        }
        $this->view->setVars(array(
            'appName'       => XhsysEnum::getEnumByNodeName('应用编号')[$appCode],
            'teacherName'   => XhsysUser::findFirst($teacherId)->sUserName,
            'tabStr'        => $tabStr,
            'schoolName'    => $schoolId ? XhschoolInfo::findFirst("iSchoolId = {$schoolId}")->sSchoolName : '校外应用',
        ));
        $classBaseArr = ['iAppCode' => $appCode, 'iTchId' => $teacherId];
        $schoolId and $classBaseArr['iSchoolId'] = $schoolId;
        $this->persistent->set('classBaseArr', $classBaseArr);                                              //设置班级基础信息
    }

    /**
     * 增加班级，如果该开班ID下已有该班级，则恢复
     * 恢复时判断op，如果为1表示为本地被删除，为2表示接口返回后被删除
     *
     * create by ck 20160816
     * modify by ck 20160929    结构更改，添加日志
     */
    public function addClassAction()
    {
        $this->view->disable();
        $this->request->isPost() or die;
        $className   = $this->request->getPost('sClassName', 'string');
        $openClassId = $this->persistent->get('openClassId');
        $class       =  XhschoolClasslist::findFirst("iSOCId = {$openClassId} AND sClassName = '{$className}'");
        if($class){
            if($class->iOp == 1) $class->bDelete = 0;       //本地新增后被删除
            elseif($class->iOp == 2) $class->iOp = 0;       //接口返回后被删除
        }
        else{
            $class = XhschoolClasslist::createRecord($openClassId, $className, null, 1);
        }
        ($class->iSCLId ? $class->updateData() : $class->insertData()) or die('fail');
        echo $class->iSCLId;
        Main::createCommitLog('class', 'class', 'edit', $class, $class->iSCLId);
    }

    /**
     * 根据班级ID删除班级
     * 如果op为0，表示为接口来数据，op改为2
     * 如果op为1，表示为本地数据，直接bDelete改为1即可
     *
     * create by ck 20160816
     * modify by ck 20160929    结构更改，添加日志
     */
    public function delClassAction(){
        $this->view->disable();
        $this->request->isPost() or die;
        $classId = $this->request->getPost('iSCLId', 'int');
        $class = XhschoolClasslist::findFirst($classId);
        if($class->iOp == 0) $class->iOp = 2;           //来自接口的返回数据
        elseif($class->iOp == 1) $class->bDelete = 1;   //本地新增的数据
        $class->updateData() or die('fail');
        echo 'success';
        Main::createCommitLog('class', 'class', 'del', $class, $class->iSCLId);
    }

    /**
     * 学生班级列表及不在班级中学生列表
     *
     * create by ck 20161010
     * modify by ck 20161101
     */
    public function studentClassListAction()
    {
        $this->view->pick('class/studentClassList');
        Assets::easyUI('js/class/studentClassList.js');
        $inSearchToolbar = Template::createSearchToolBar([
            ['type'=>'text', 'id'=>'InList_Search', 'label'=>'搜索：'],
            ['type'=>'button', 'id'=>'bt_InList_Search', 'text'=>'确定', 'icon'=>'fa-search', 'style'=>'margin-left:10px']
        ]);
        $outSearchToolbar = Template::createSearchToolBar([
            ['type'=>'select', 'id'=>'OutList_Search_Item', 'multiple' => 'true', 'style'=>'width:80px;', 'data'=>[
                    ''              => '默认',
                    'sAdClsName'    => '班级',
                    'sUserName'     => '姓名',
                    'sLogonName'    => '登陆名',
                    'sSelfPhone'    => '电话'
                ]
            ],
            ['type'=>'text', 'id'=>'OutList_Search'],
            ['type'=>'button', 'id'=>'bt_OutList_Search', 'text'=>'搜索', 'icon'=>'fa-search', 'style'=>'margin-left:10px']
        ]);
        $this->view->setVars(array(
            'InList'    => Template::createList('InList', 'XHSys_User', [
                'field'         => ['iUserId', 'sUserName', 'sLogonName', 'sSelfPhone', 'iUserSex', 'sAdClsName'],
                'tableAttr'     => ['title' => '班级学生'],
                'searchToolbar' => $inSearchToolbar
            ]),
            'OutList'   => Template::createList('OutList', 'XHSys_User', [
                'field'     => ['iUserId', 'sUserName', 'sLogonName', 'sSelfPhone', 'iUserSex', 'sAdClsName'],
                'tableAttr' => ['title' => '选择学生'],
                'searchToolbar' => $outSearchToolbar
            ])
        ));
    }

    /**
     * 根据班级ID，获取该班级下学生信息
     *
     * create by ck 20160815
     * modify by ck 20160928    sql语句更改
     * modify by ck 20161010    增加模糊查询
     */
    public function getStudentInClassDgDataAction()
    {
        $this->view->disable();
        $this->request->isPost() or die;
        $classId = $this->request->getPost('iSCLId');
        $conditions = 'S.iSCLId = :iSCLId: AND S.bDelete = 0 AND S.iOp <> 2 AND U.bDelete = 0 AND U.iUserType = 1';
        Main::runSearchVagueConditions($conditions, ['U.sUserName', 'U.sAdClsName', 'U.sLogonName']);
        $builder = $this->modelsManager->createBuilder()
            ->columns(['U.iUserId', 'U.sLogonName', 'U.sUserName', 'U.sSelfPhone', 'U.iUserSex', 'U.sAdClsName'])
            ->from(['S' => '\\Admin\\Models\\school\\XhschoolClassstudent'])
            ->leftJoin('\\Admin\\Models\\user\\XhsysUser', 'U.iUserId = S.iStudId', 'U')
            ->where($conditions, ['iSCLId' => $classId]);
        echo Main::runBuilderPaginator($builder);
    }

    /**
     * 获取该校范围内，不在该班级中的学生名单
     *
     * create by ck 20160816
     * modify by ck 20160929    sql语句更改
     * modify by ck 20161020    schoolId从classBaseArr中获取，无信息则赋为0
     */
    public function getStudentOutClassDgDataAction()
    {
        $this->view->disable();
        $this->request->isPost() or die;
        $classId    = $this->request->getPost('iSCLId', 'int');
//        $schoolId   = $this->request->getPost('iSchoolId', 'int');
        $classBaseArr = $this->persistent->get('classBaseArr');
        $schoolId   = isset($classBaseArr['iSchoolId']) ? $classBaseArr['iSchoolId'] : 0;
        $queryArr   = XhschoolClassstudent::createSqlForOutStudByClassId($classId, $schoolId);
        Main::runSearchVagueConditions($queryArr['query'], ['sUserName', 'sAdClsName', 'sLogonName', 'iUserId']);
        echo Main::runSqlPaginator($queryArr);
    }

    /**
     * 向班级中添加学生，如班级中已有该学生且op为2（表示本地删除，服务端存在）恢复为0
     * 其他学生新增，op为1
     *
     * create by ck 20160816
     * modify by ck 20160930    结构更改
     */
    public function addStudentInClassAction()
    {
        $this->view->disable();
        $this->request->isPost() or die;
        $classId    = $this->request->getPost('iSCLId');
        $studIdArr  = explode(',', $this->request->getPost('ids'));
        $totalStudId = $studIdArr;
        $dbRollback = false;
        $this->db->begin();
        if(!XhschoolClassstudent::addOriginalStudIntoClass($studIdArr, $classId)){
            $this->db->rollback();
            die;
        }
        if(!XhschoolClassstudent::batchCreateStudent($studIdArr, $classId, 1)){
            $dbRollback = true;
        }
        if($dbRollback) {
            $this->db->rollback();
            die;
        }
        $this->db->commit();
        Main::createCommitLog('class', 'classStudent', 'add', ['studId' => $totalStudId, 'newStudId' => $studIdArr, 'classId' => $classId], $classId, '新增学生到班级中（studId为总学生ID，newStudId为本地新增）');
    }

    /**
     * 从班级中删除某些学生
     * 如果该学生为本地新增，则直接bDelete删除，如果为接口返回，则op=2
     *
     * create by ck 20160816
     */
    public function delStudentInClassAction()
    {
        $this->view->disable();
        $this->request->isPost() or die;
        $studIdArr = explode(',', $this->request->getPost('ids'));
        $classId   = $this->request->getPost('iSCLId');
        $this->db->begin();
        if(!XhschoolClassstudent::delStudOutClass($studIdArr, $classId)){
            $this->db->rollback();
            die('（109107005）删除失败');
        }
        echo '删除成功！';
        $this->db->commit();
        Main::createCommitLog('class', 'classStudent', 'del', ['studId' => $studIdArr, 'classId' => $classId], '从班级中删除学生（studId包括本地及远程数据）');
    }

    /**
     * 完成开课
     * 根据开班的op选择提交的内容和方式
     * 如果op为1，表示为本地新建，调用新建方法
     * 如果op为0，表示接口返回的数据，调用修改方法
     *
     * create by ck 20160816
     */
    public function completeOpenClassAction()
    {
        $this->view->disable();
        $openClassId = $this->persistent->get('openClassId');
        $openClass   = XhschoolOpenclass::findFirst($openClassId);
        if($openClass->iOp == 1) {
            echo $this->submitClassInfoWithNew($openClassId);
        }
        elseif($openClass->iOp == 0) {
            echo $this->submitClassInfoWithModify($openClassId);
        }
    }

    /**
     * 将数据库中未被删除的数据组合后提交新建班级
     *
     * @param $openClassId
     * @return string
     *
     * create by ck 20160816
     * modify by ck 20161228    如果为古文刷题王，则使用另外的ip
     */
    function submitClassInfoWithNew($openClassId)
    {
        $K = $this->persistent->get('classBaseArr');
        $teacherInfo = XhschoolClassteacher::findByOpenClassId($openClassId);
        foreach($teacherInfo as $teacher){
            $K['oTeacher'][] = array('iTchId' => $teacher->iTchId);
        }
        $classInfo = XhschoolClasslist::findByOpenClassId($openClassId);
        foreach($classInfo as $class){
            $classArr = array('sClassName' => $class->sClassName);
            $studentInfo = XhschoolClassstudent::findByClassId($class->iSCLId);
            foreach($studentInfo as $student){
                $classArr['oStudent'][] = array('iStuId' => $student->iStudId);
            }
            $K['oClass'][] = $classArr;
        }
        if(!isset($K['oTeacher']) && !isset($K['oClass'])) return Main::showMessageModal('无变更信息，无法提交！', 109107013);

        //add by ck 20161228    临时
//        if(in_array($K['iAppCode'], ['1200'])){
//            $gwConfig = Main::getConfigByName('cRelation');
//            $gwConfig['ip'] = $gwConfig['gw'];
//            unset($gwConfig['gw']);
//            $data = Main::transitToCInterface($gwConfig, 'Web_CreateClass', $K);
//        }
//        else{
            $data = Main::transitToCInterface('cRelation', 'Web_CreateClass', $K);
//        }

//        $data = Main::transitToCInterface('cRelation', 'Web_CreateClass', $K);
        $data = json_decode($data, true);
        if($data['R'] == 200) return 'success:'.json_encode($K);
        return Main::showMessageModal($data['I'].$data['M'], true) . ':' . json_encode($K);
    }

    /**
     * 将数据库中未被删除，op不等于0的数据组合后提交修改班级
     *
     * @param $openClassId
     * @return string
     *
     * create by ck 20160816
     * modify by ck 20161228    如果为古文刷题王，则使用另外的ip
     */
    function submitClassInfoWithModify($openClassId)
    {
        $K = $this->persistent->get('classBaseArr');
        $teacherInfo = XhschoolClassteacher::findByOpenClassId($openClassId);
        foreach($teacherInfo as $teacher){
            if($teacher->iOp != 0) $K['oTeacher'][] = array('iTchId' => $teacher->iTchId, 'op' => $teacher->iOp);
        }
        $classInfo = XhschoolClasslist::findByOpenClassId($openClassId);
        foreach($classInfo as $class){
            $classArr = array();
            switch($class->iOp){
                case 1: //新增班级
                    $classArr = array('sClassName' => $class->sClassName, 'op' => 1);
                    $studentInfo = XhschoolClassstudent::findByClassId($class->iSCLId);
                    foreach($studentInfo as $student){
                        $classArr['oStudent'][] = array('iStuId' => $student->iStudId);
                    }
                    break;
                case 2: //删除
                    $classArr = array('iClassId' => $class->sClassId, 'op' => 2);
                    break;
                case 0: //更新
                    $classArr = array('iClassId' => $class->sClassId, 'op' => 3);
                    $studentInfo = XhschoolClassstudent::findByClassId($class->iSCLId);
                    foreach($studentInfo as $student){
                        if($student->iOp != 0) $classArr['oStudent'][] = array('iStuId' => $student->iStudId, 'op' => $student->iOp);
                    }
                    if(!isset($classArr['oStudent'])){//没有学生变动
                        continue 2;
                    }
                    break;
            }
            $classArr and $K['oClass'][] = $classArr;
        }
        if(!isset($K['oTeacher']) && !isset($K['oClass'])) return Main::showMessageModal('无变更信息，无法提交！', 109107007);

        //add by ck 20161228    临时
//        if(in_array($K['iAppCode'], ['1200'])){
//            $gwConfig = Main::getConfigByName('cRelation');
//            $gwConfig['ip'] = $gwConfig['gw'];
//            unset($gwConfig['gw']);
//            $data = Main::transitToCInterface($gwConfig, 'Web_UpdateClass', $K);
//        }
//        else{
            $data = Main::transitToCInterface('cRelation', 'Web_UpdateClass', $K);
//        }

//        $data = Main::transitToCInterface('cRelation', 'Web_UpdateClass', $K);
        $data = json_decode($data, true);
        if($data['R'] == 200) return 'success:'.json_encode($K);
        return  Main::showMessageModal($data['I'].$data['M'], true) . ':' . json_encode($K);
    }

    /**
     * 教师开班信息查看页面
     *
     * create by ck 20161009
     * modify by ck 20170409    更改下拉框样式，增加筛选
     */
    public function teacherClassListAction()
    {
        $this->view->pick('class/teacherClassList');
        $this->assets->addCss('assets/easyui/themes/metro/tabs.css');
        Assets::importMainJs('assets/easyui/jquery.easyui.min.js');
        Assets::select2('js/class/teacherClassList.js');
        $this->view->setVar('appList', XhsysEnum::getEnumByNodeName('应用编号'));
    }

    /**
     * 根据教师ID，学校ID，应用编号获取教师班级信息，以json形式返回
     *
     * create by ck 20161009
     */
    public function getClassInfoByTeacherAction()
    {
        $this->view->disable();
        $teacherId = $this->request->getPost('iTeacherId', 'int');
        $schoolId  = $this->request->getPost('iSchoolId', 'int');
        $appCode   = $this->request->getPost('iAppCode', 'string');
        $teacherId && $schoolId && $appCode or die(Main::runErrorInterfaceInfo(109107009, '参数不完整'));
        XhappStore::checkAppOutSchool($appCode) and $schoolId = 0;                     //如果为独立应用则设置学校ID为0
        $K = ['iAppCode' => $appCode, 'iTchId' => $teacherId];
        $schoolId and $K['iSchoolId'] = $schoolId;                                  //学校ID为0则不添加到参数中
        $data = Main::transitToCInterface('cRelation', 'Web_GetStudTeacGroup', $K);
        $data = json_decode($data, true);
        if($data['R'] == 200) {                                                      //已有信息
            if (!self::deleteOldClassInfo($schoolId, $appCode, $teacherId)) {
                die(Main::runErrorInterfaceInfo(109107010, '清理原记录失败，无法继续操作'));
            }
            $unitInfo = json_decode($data['D'], true)[0];
            $openClassId = $this->insertUnitData($unitInfo);
            $openClassId or die(Main::runErrorInterfaceInfo(109107011, '数据插入失败'));
            $classInfoArr = XhschoolClasslist::findByOpenClassId($openClassId);
            $classArr = [];
            foreach($classInfoArr as $classInfo){                                                               //组成tab
                $frameSrc  = $this->url->getBaseUri() . "Class/studentInClassList?iSchoolId={$schoolId}&iSCLId={$classInfo->iSCLId}";
                $classArr[] = ['title'=>$classInfo->sClassName, 'src'=> $frameSrc];
            }
            echo Main::runSuccessInterfaceInfo($classArr);
        }
        else{
            echo Main::runSuccessInterfaceInfo([]);
        }
    }

    /**
     * 班级学生列表视图（不可操作）
     *
     * create by ck 20161009
     */
    public function studentInClassListAction()
    {
        $this->view->pick('class/studentInClassList');
        Assets::easyUI('js/class/studentInClassList.js');
        $this->view->setVars(array(
            'List'  => Template::createList('List', 'XHSys_User', array(
                'field'     => ['iUserId','sUserName','sLogonName','sSelfPhone','iUserSex'],
                'checkbox'  => false,
                'tableAttr' => ['singleSelect' => 'true']
            ))
        ));
    }

    /**
     * 学生列表页面，展示在班级中的学生，可新增或删除
     *
     * create by ck 20160815
     * modify by ck 20160929    js压缩
     */
//    public function studentInClassListAction()
//    {
//        $this->view->pick('class/studentInClassList');
//        Assets::easyUI('js/class/studentInClassList.js');
//        $listButtonArr = array();
//        $listButtonArr[] = array('id'=>'bt_list_add', 'text'=>'增加', 'plain'=>'true', 'icon'=>'fa-plus');
//        $listButtonArr[] = array('id'=>'bt_list_del', 'text'=>'删除', 'plain'=>'true', 'icon'=>'fa-trash');
//        $buttonToolbar = Template::createButtonToolBar($listButtonArr);
//        $this->view->setVars(array(
//            'List'          => Template::createList('List', 'XHSys_User', array(
//                'buttonToolbar' => $buttonToolbar,
//                'field'         => array('iUserId','sUserName','sLogonName','sSelfPhone','iUserSex')
//            ))
//        ));
//    }

    /**
     * 不在班级中的学生列表页面
     *
     * create by ck 20160816
     * modify by ck 20160929    js压缩
     */
//    public function studentOutClassListAction()
//    {
//        $this->view->pick('class/studentOutClassList');
//        Assets::easyUI('js/class/studentOutClassList.js');
//        $listSearchArr = array();
//        $listSearchArr[] = array('type'=>'text', 'id'=>'list_search', 'label'=>'搜索： ');
//        $searchToolbar = Template::createSearchToolBar($listSearchArr);
//        $this->view->setVars(array(
//            'List'          => Template::createList('List', 'XHSys_User', array(
//                'field'         => array('iUserId','sUserName','sLogonName','sSelfPhone','iUserSex'),
//                'searchToolbar' => $searchToolbar,
//            ))
//        ));
//    }

    /**
     * 删除已存在数据库的旧记录，无记录或成功返回true，否则返回false
     *
     * @param $schoolId
     * @param $appCode
     * @param $teacherId
     * @return bool
     *
     * create by ck 20160815
     * modify by ck 20160929
     */
//    public function deleteOldClassInfo($schoolId, $appCode, $teacherId){
//        $openClassId = XhschoolOpenclass::getOldOpenClassId($schoolId, $appCode, $teacherId);
//        if(!$openClassId) return true;
//        $this->db->begin();
//        $dbRollback = false;
//        //删除旧开班
//        $oldOpenClass = XhschoolOpenclass::findFirst($openClassId);
//        $oldOpenClass -> bDelete = 1;
//        if(!Main::editData($oldOpenClass,true)){
//            $dbRollback = true;
//            goto dealTrans;
//        }
//        //删除旧教师记录
//        $sql = "UPDATE XhschoolClassteacher SET bDelete = 1 WHERE iSOCId = :iOpenClassId:";
//        $result = $this->modelsManager->executeQuery($sql,array(
//            'iOpenClassId' => $openClassId
//        ));
//        if(!$result){
//            $dbRollback = true;
//            goto dealTrans;
//        }
//        //删除旧班级记录
//        $sql = "UPDATE XhschoolClasslist SET bDelete = 1 WHERE iSOCId = :iOpenClassId:";
//        $result = $this->modelsManager->executeQuery($sql,array(
//            'iOpenClassId' => $openClassId
//        ));
//        if(!$result){
//            $dbRollback = true;
//            goto dealTrans;
//        }
//        //删除旧学生记录
////            $classIdArr = XhschoolClasslist::find(array(
////                'conditions'    => "iSOCId = {$openClassId}"
////            ))->toArray();
////            $classId = array();
////            foreach($classIdArr as $classArr) $classId[] = (string)$classArr['iSCLId'];
////            $classId = implode(',', $classId);
////            $sql = "UPDATE XhschoolClassstudent AS stud SET stud.bDelete = 1 WHERE stud.iSCLId IN ({$classId})";
//        //原方法
//        $sql = "UPDATE XhschoolClassstudent AS stud SET stud.bDelete = 1 WHERE stud.iSCLId IN (SELECT class.iSCLId FROM XhschoolClasslist AS class WHERE class.iSOCId = {$openClassId})";
//        $result = $this->modelsManager->executeQuery($sql);
//        if(!$result){
//            $dbRollback = true;
//            goto dealTrans;
//        }
//        dealTrans:
//        if($dbRollback) $this->db->rollback();
//        $this->db->commit();
//        return $dbRollback ? false : true;
//    }

    /**
     * @param $schoolId
     * @param $appCode
     * @param $teacherId
     * @return bool
     * 根据参数从C++获取师生关系
     * 获取到则插入数据库中(op=0)，无数据则新建记录(op=1)
     * create by ck 20160815
     */
//    public function insertClassInfo(&$schoolId, $appCode, $teacherId){
//        $K = array(
//            'iAppCode'  => $appCode,
//            'iTchId'    => $teacherId
//        );
//        if($schoolId) $K['iSchoolId'] = $schoolId;
//        $data = Main::transitToCInterface('cRelation', 'Web_GetStudTeacGroup', $K);
//        $data = json_decode($data, true);
//        $dbRollback = false;
//        $this->db->begin();
//        if($data['R'] == 200){  //已有师生关系
//            self::deleteOldClassInfo($schoolId, $appCode, $teacherId) or die(Main::showMessageModal('清理原记录失败，无法继续操作！', true));
//            $unitInfo   = json_decode($data['D'], true);
//            $unitInfo   = $unitInfo[0];
//            if(isset($unitInfo['iSchoolId'])) $schoolId = $unitInfo['iSchoolId'];
//            $openClass  = XhschoolOpenclass::createRecord($unitInfo, 0);
//            if(!Main::insertData($openClass, true)){
//                $dbRollback = true;
//                goto dealTrans;                                                                                     //跳出
//            }
//            foreach($unitInfo['oTeacher'] as $teacherInfo){
//                $teacher = XhschoolClassteacher::createRecord($teacherInfo, $openClass->iSOCId, 0);
//                if(!Main::insertData($teacher, true)){
//                    $dbRollback = true;
//                    goto dealTrans;
//                }
//            }
//            foreach($unitInfo['oClass'] as $classInfo){
//                $class = XhschoolClasslist::createRecord($classInfo, $openClass->iSOCId, 0);
//                if(!Main::insertData($class, true)){
//                    $dbRollback = true;
//                    goto dealTrans;
//                }
//                foreach($classInfo['oStudent'] as $studentInfo){
//                    $student = XhschoolClassstudent::createRecord($studentInfo['iStuId'], $class->iSCLId, 0);
//                    if(!Main::insertData($student, true)){
//                        $dbRollback = true;
//                        goto dealTrans;
//                    }
//                }
//            }
//        }
//        else{   //不存在师生关系
////跳过旧记录
//            $openClassId = XhschoolOpenclass::getOldOpenClassId($schoolId, $appCode, $teacherId);
//            if($openClassId) {
//                $this->persistent->set('openClassId', $openClassId);
//                return true;
//            }
//            $openClass = XhschoolOpenclass::createRecord(array('iAppCode' => $appCode, 'iSchoolId' => $schoolId), 1);
//            if(!Main::insertData($openClass, true)){
//                $dbRollback = true;
//                goto dealTrans;
//            }
//            $teacher = XhschoolClassteacher::createRecord(array('iTchId' => $teacherId), $openClass->iSOCId, 1);
//            if(!Main::insertData($teacher, true)){
//                $dbRollback = true;
//                goto dealTrans;
//            }
//        }
//        dealTrans:
//        if($dbRollback) $this->db->rollback();
//        else {
//            $this->persistent->set('openClassId', $openClass->iSOCId);      //设置开班ID
//            $this->db->commit();
//        }
//        return !$dbRollback;
//    }

}

